package cn.broadmax.boot.config;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Profile({"dev","test"})
@Configuration
@EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {

    @Bean
    public Docket createSysApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("jexx")
                .apiInfo(createApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.broadmax.boot.modules"))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(createHeaderToken());
    }


    private List<Parameter> createHeaderToken(){
        List<Parameter> parameters = new ArrayList<>();

        ParameterBuilder parameterBuilder = new ParameterBuilder();
        parameterBuilder.name("Authorization")
                .parameterType("header")
                .defaultValue("Bearer ")
                .description("以 \"Bearer \" 开头,后面有个空格")
                .modelRef(new ModelRef("string"))
                .required(false)
                .build();
        parameters.add(parameterBuilder.build());
        return parameters;
    }

    private ApiInfo createApiInfo() {
        return new ApiInfoBuilder()
                .title("jexx-boot后台服务API接口")
                .version("1.0.0")
                .description("jexx-boot")
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}
